'use client';

import {
  createContext,
  useContext,
  ReactNode,
  useMemo,
} from 'react';
import { useQuery } from '@tanstack/react-query';
import { getMenuList } from '@/apis/client/menu';
import { Menu } from '@/types/menu';

interface MenuContextType {
  menus: Menu[];
  isLoading: boolean;
  error: Error | null;
}

const MenuContext = createContext<MenuContextType | undefined>(undefined);

export function MenuProvider({ children }: { children: ReactNode }) {
  const { data: menus = [], isLoading, error } = useQuery({
    queryKey: ['menus'],
    queryFn: () => getMenuList({}),
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
    gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
  });



  return (
    <MenuContext.Provider value={{ 
      menus, 
      isLoading, 
      error: error as Error | null 
    }}>
      {children}
    </MenuContext.Provider>
  );
}

export function useMenu() {
  const context = useContext(MenuContext);
  if (context === undefined) {
    throw new Error('useMenu must be used within a MenuProvider');
  }
  return context;
}